C++ program to find the GCD of two numbers 您所在的位置:网站首页 cpp gcd C++ program to find the GCD of two numbers

C++ program to find the GCD of two numbers

#C++ program to find the GCD of two numbers| 来源: 网络整理| 查看: 265

next → ← prev C++ program to find the GCD of two numbers

In this tutorial, we will write a c++ program to find the GCD of two numbers.

GCD (Greatest common divisor) is also known as HCF (Highest Common Factor).

For example

36 = 2 * 2 * 3 * 3

60 = 2 * 2 * 3 * 5

The highest common factor of the two numbers is 2, 2, and 3.

So, the HCF of two numbers is 2 * 2 * 3 = 12

20 = 2 * 2 * 5

28 = 2 * 2 * 7

The highest common factor of the two numbers is 2 and 2.

So, the HCF of two numbers is 2 * 2 = 4.

Approach 1

The problem can be solved by finding all the prime factors of the two numbers and then find common factors and return their product.

Find the factors of the first number Find the factors of the second number Find common factors of both numbers Multiply them to get GCD

C++ code

Output

GCD of 36 and 60 is 12

Approach 2

Approach 1 can be solved in an efficient way using the Euclidean algorithm. This algorithm follows the idea that GCD does not change if the smaller number gets subtracted from the larger one.

C++ code

Output

GCD of 36 and 60 is 12

Approach 3

Approach two can be optimized further to use a modulo operator instead of subtraction.

C++ code

Output

GCD of 60 and 36 is 12 Next TopicC++ program to find greatest of four numbers ← prev next →


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有